package action;

import dao.BookDao;
import dao.OrderDao;
import dao.OrderItemDao;
import po.Book;
import po.Order;
import po.OrderItem;
import po.User;
import utils.DateCoverter;
import vo.OrderItemVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet(urlPatterns = "/user/action/BuyNowServlet")
public class BuyNowServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // 1.获取参数
        String product = req.getParameter("product");
        Integer count = Integer.parseInt(req.getParameter("count"));
         //2.从session中获取user对象
        User user = (User)req.getSession().getAttribute("user");
        String phone = user.getPhone();
         //3.创建Order对象
        Order order = new Order();
         //4.设置订单对象的属性值 订单id，用户id，状态：待处理
        order.setOrderId(phone.substring(phone.length()-3) + DateCoverter.formatTimeStamp(new Date())); //substring(4，6) 从第下标为四开始，到第六位截止，含头不含尾
        order.setUserId(user.getPhone());
        order.setSta("待处理");
         //5.设置book对象的isbn值
        Book book = new Book();
        book.setIsbn(product);
         //6.进入bookdao，根据isbn查询该商品的所有信息
        BookDao bookDao = new BookDao();
        Book book1 = bookDao.selectByIsbn(book);
         //7.持久化订单，调用OrderDao的insert方法
        OrderDao orderDao = new OrderDao();
        orderDao.insert(order);
         //8.创建订单货物对象
        OrderItem orderItem = new OrderItem();
         //9.设置属性值
        orderItem.setCount(count);
        orderItem.setOrderId(order.getOrderId());
        orderItem.setPrice(book1.getPrice());
        orderItem.setProduct(product);
         //10.持久化订单货物，调用OrderItemDao的insert方法
        OrderItemDao orderItemDao = new OrderItemDao();
        orderItemDao.insert(orderItem);
         //11.跳转到OrderConfirmServlet(查询确认订单页面需要的信息)
         req.getRequestDispatcher("../action/OrderConfirmServlet?orderId="+order.getOrderId()).forward(req,resp);

    }
}
